// vuex的权限模块
import { asyncRoutes, constantRoutes } from '@/router'

function hasPermission(roles, route) {
  if (!route.name) return false
  return roles.includes(route.name)
}

export function filterAsyncRoutes(routes, menus) {
  const res = []

  routes.forEach((route) => {
    const tmp = { ...route }
    if (hasPermission(menus, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, menus)
      }
      res.push(tmp)
    } else if (tmp.children) {
      // 即使父路由没权限，也要检查子路由
      const childRoutes = filterAsyncRoutes(tmp.children, menus)
      if (childRoutes.length > 0) {
        tmp.children = childRoutes
        res.push(tmp)
      }
    }
  })

  return res
}

// vuex中的permission模块用来存放当前的 静态路由 + 当前用户的 权限路由
const state = {
  routes: constantRoutes // 所有人默认拥有静态路由
}
const mutations = {
  // newRoutes可以认为是 用户登录 通过权限所得到的动态路由的部分
  setRoutes(state, newRoutes) {
    // 应该是每次更新 都应该在静态路由的基础上进行追加
    state.routes = [...constantRoutes, ...newRoutes]
  }
}
const actions = {
  // 筛选权限路由
  // 第二个参数为当前用户的所拥有的菜单权限
  // menus: ["settings","permissions"]
  // asyncRoutes是所有的动态路由
  // asyncRoutes  [{path: 'setting',name: 'setting'},{}]
  filterRoutes(context, menus) {
    try {
      const routes = filterAsyncRoutes(asyncRoutes, menus)
      context.commit('setRoutes', routes)
      return routes
    } catch (error) {
      console.error('路由过滤错误:', error)
      return []
    }
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
